<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>文件上传</title>
  </head>
  <script src="./axios.min.js"></script>
  <script src="./md5.min.js"></script>
  <script src="./qs.js"></script>
  <body>
    <h2>上传文件</h2>
    <form id="uploadForm" enctype="multipart/form-data">
      <label for="fileInput">选择文件:</label>
      <input type="file" id="fileInput" name="file" multiple />
      <br /><br />
      <button type="button" onclick="getFile()">上传文件</button>
      <div>
        <span>当前上传进度：</span>
        <span id="percent"></span>
      </div>
    </form>

    <script>
      // 计算文件的SHA-256哈希值
      function calculateFileHash(file) {
        const reader = new FileReader();

        // 使用Promise处理异步操作
        return new Promise((resolve, reject) => {
          reader.onload = function (event) {
            // 获取文件的ArrayBuffer
            const fileBuffer = event.target.result;

            // 使用SubtleCrypto API计算SHA-256哈希
            crypto.subtle
              .digest("SHA-256", fileBuffer)
              .then((hashBuffer) => {
                // 将哈希Buffer转为十六进制字符串
                const hashArray = Array.from(new Uint8Array(hashBuffer));
                const hashHex = hashArray
                  .map((byte) => byte.toString(16).padStart(2, "0"))
                  .join("");
                resolve(hashHex);
              })
              .catch(reject);
          };

          reader.onerror = reject;
          reader.readAsArrayBuffer(file); // 以ArrayBuffer方式读取文件
        });
      }
    </script>

    <script>
      async function upload(file) {
        const formData = new FormData();
        formData.append("file", file);
        const res = await axios.post(`/file/upload`, formData, {
          headers: {
            "Content-Type": "multipart/form-data", // 指定表单数据类型
          },
        });
      }

      async function getFile() {
        // 获取文件输入框
        const fileInput = document.getElementById("fileInput");

        // 获取用户选择的文件列表
        const files = fileInput.files;

        const file = files[0];
        const hash = await calculateFileHash(file);

        await upload(file, hash);
      }
    </script>
  </body>
</html>
